const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const axios = require('axios')
require("dotenv").config();

router.post('/login', async (req, res) => {
  try {
    const { code } = req.body
    const response = await axios.get(
      "https://api.weixin.qq.com/sns/jscode2session",
      {
        params: {
          appid: process.env.WECHAT_APPID,
          secret: process.env.WECHAT_SECRET,
          js_code: code,
          grant_type: "authorization_code",
        },
      }
    );
    console.log(response)
    const { openid, session_key } = response.data;

    if (!openid) {
      return res.status(400).json({ message: '缺少openid参数' });
    }

    // 查找或创建用户
    let user = await User.findOne({ where: { openid } });

    if (!user) {
      // 如果用户不存在,创建新用户
      user = await User.create({ openid });
    }

    // 生成JWT token
    const token = jwt.sign(
      { id: user.id, openid: user.openid },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRES_IN }
    );

    res.json({
      token,
      userInfo: {
        id: user.id,
        nickname: user.nickname,
        gender: user.gender,
        avatar: user.avatar,
        age: user.age,
        phone: user.phone,
        openid: user.openid,
        warningNum: user.warningNum
      }
    });

  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router;
